package com.qf.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 抽取servlet共同部分
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("utf-8");
        //1获取参数中的method
        String param = req.getParameter("method");
        //2获取要执行的方法对象（反射）
        try {
            //通过反射获取要执行的方法
            Method method = this.getClass().getMethod(param, HttpServletRequest.class, HttpServletResponse.class);
            //执行方法 result就是方法的返回值
            //如果method是void，则返回null

            Object result = method.invoke(this, req, resp);
            if (result==null) {
                //认为前端时ajax

                //否则需要重定向，请求转发
            }else {
                String res = result.toString();
                //如果是重定向：约定前缀为 redirect
                if(res.startsWith("redirect:")){
                    //对res进行切割
                    String[] arr = res.split(":");
                    if (arr!=null && arr.length>1) {
                        resp.sendRedirect(arr[1]);
                    }


                }
                //如果是请求转发：约定前缀为 forward
                String[] arr = res.split(":");
                if (arr!=null && arr.length>1) {
                }
                req.getRequestDispatcher(arr[1]).forward(req,resp);
            }

        } catch (Exception e) {
                e.printStackTrace();
                System.out.println("调用方法失败！！！");
            }


        }


    }

